/**
 * React Native 使用示例
 * 
 * 演示如何在React Native项目中使用网络调试客户端
 * 无需安装任何依赖包！
 */

import React, { useEffect, useState } from 'react'
import {
  View,
  Text,
  TouchableOpacity,
  TextInput,
  Alert,
  StyleSheet,
} from 'react-native'

// 导入调试客户端（复制到您的项目中）
import './utils/debugClient' // 这个文件无需任何依赖

const ExampleScreen: React.FC = () => {
  const [username, setUsername] = useState('')
  const [count, setCount] = useState(0)

  useEffect(() => {
    // 页面生命周期日志
    global.$debug.pageEvent('ExampleScreen', 'mounted')
    
    // 测试连接
    global.$debug.testConnection()
    
    return () => {
      global.$debug.pageEvent('ExampleScreen', 'unmounted')
    }
  }, [])

  const handleBasicLogging = () => {
    global.$debug.debug('这是调试信息')
    global.$debug.info('这是普通信息')
    global.$debug.warn('这是警告信息')
    global.$debug.error('这是错误信息')
  }

  const handleTableData = () => {
    const users = [
      { id: 1, name: 'Alice', age: 25, city: 'Beijing' },
      { id: 2, name: 'Bob', age: 30, city: 'Shanghai' },
      { id: 3, name: 'Charlie', age: 35, city: 'Guangzhou' },
    ]
    
    global.$debug.table(users, '用户列表')
  }

  const handleUserAction = () => {
    setCount(prev => prev + 1)
    
    global.$debug.userAction('button_click', {
      buttonName: 'increment',
      newCount: count + 1,
      timestamp: Date.now()
    })
  }

  const handleNetworkRequest = async () => {
    global.$debug.info('开始网络请求')
    global.$debug.time('API请求耗时')
    
    try {
      const requestData = { username, action: 'login' }
      
      // 模拟网络请求
      const response = await fetch('https://jsonplaceholder.typicode.com/posts/1')
      const responseData = await response.json()
      
      global.$debug.timeEnd('API请求耗时')
      
      // 记录网络请求
      global.$debug.networkLog(
        'GET',
        'https://jsonplaceholder.typicode.com/posts/1',
        requestData,
        responseData,
        500 // 假设耗时500ms
      )
      
      global.$debug.info('网络请求成功', responseData)
      
      Alert.alert('成功', '请求完成，请查看调试面板')
    } catch (error) {
      global.$debug.timeEnd('API请求耗时')
      global.$debug.errorLog(error, 'handleNetworkRequest')
      
      Alert.alert('错误', '网络请求失败')
    }
  }

  const handlePerformanceTest = () => {
    global.$debug.time('性能测试')
    
    // 模拟一些计算密集的操作
    let result = 0
    for (let i = 0; i < 100000; i++) {
      result += Math.random()
    }
    
    const duration = Math.random() * 100 + 50 // 模拟50-150ms
    
    global.$debug.performanceLog('计算密集操作', duration, {
      iterations: 100000,
      result: result.toFixed(2)
    })
    
    global.$debug.timeEnd('性能测试')
  }

  const handleErrorTest = () => {
    try {
      // 故意制造一个错误
      const obj = null
      obj.someProperty.toString()
    } catch (error) {
      global.$debug.errorLog(error, 'handleErrorTest')
    }
  }

  const handleClearLogs = () => {
    global.$debug.clear()
    Alert.alert('已清空', '远程日志已清空')
  }

  const showDebugStatus = () => {
    const status = global.$debug.getStatus()
    
    global.$debug.info('调试状态', status)
    
    Alert.alert(
      '调试状态',
      `环境: ${status.environment}\n` +
      `启用: ${status.enabled ? '是' : '否'}\n` +
      `服务器: ${status.serverUrl}`
    )
  }

  return (
    <View style={styles.container}>
      <Text style={styles.title}>网络调试客户端测试</Text>
      
      <View style={styles.inputContainer}>
        <Text style={styles.label}>用户名：</Text>
        <TextInput
          style={styles.input}
          value={username}
          onChangeText={(text) => {
            setUsername(text)
            global.$debug.userAction('input_change', { 
              field: 'username', 
              length: text.length 
            })
          }}
          placeholder="输入用户名"
        />
      </View>

      <View style={styles.buttonContainer}>
        <TouchableOpacity style={styles.button} onPress={handleBasicLogging}>
          <Text style={styles.buttonText}>基础日志测试</Text>
        </TouchableOpacity>

        <TouchableOpacity style={styles.button} onPress={handleTableData}>
          <Text style={styles.buttonText}>表格数据测试</Text>
        </TouchableOpacity>

        <TouchableOpacity style={styles.button} onPress={handleUserAction}>
          <Text style={styles.buttonText}>用户操作 ({count})</Text>
        </TouchableOpacity>

        <TouchableOpacity style={styles.button} onPress={handleNetworkRequest}>
          <Text style={styles.buttonText}>网络请求测试</Text>
        </TouchableOpacity>

        <TouchableOpacity style={styles.button} onPress={handlePerformanceTest}>
          <Text style={styles.buttonText}>性能测试</Text>
        </TouchableOpacity>

        <TouchableOpacity style={styles.button} onPress={handleErrorTest}>
          <Text style={styles.buttonText}>错误测试</Text>
        </TouchableOpacity>

        <TouchableOpacity style={[styles.button, styles.clearButton]} onPress={handleClearLogs}>
          <Text style={styles.buttonText}>清空日志</Text>
        </TouchableOpacity>

        <TouchableOpacity style={[styles.button, styles.statusButton]} onPress={showDebugStatus}>
          <Text style={styles.buttonText}>调试状态</Text>
        </TouchableOpacity>
      </View>

      <View style={styles.infoContainer}>
        <Text style={styles.infoText}>
          📱 在浏览器打开调试面板查看实时日志
        </Text>
        <Text style={styles.infoText}>
          🌐 http://192.168.1.100:3000/debug-panel.html
        </Text>
      </View>
    </View>
  )
}

const styles = StyleSheet.create({
  container: {
    flex: 1,
    padding: 20,
    backgroundColor: '#f5f5f5',
  },
  title: {
    fontSize: 24,
    fontWeight: 'bold',
    textAlign: 'center',
    marginBottom: 30,
    color: '#333',
  },
  inputContainer: {
    marginBottom: 20,
  },
  label: {
    fontSize: 16,
    marginBottom: 5,
    color: '#666',
  },
  input: {
    borderWidth: 1,
    borderColor: '#ddd',
    borderRadius: 8,
    padding: 12,
    fontSize: 16,
    backgroundColor: 'white',
  },
  buttonContainer: {
    flex: 1,
  },
  button: {
    backgroundColor: '#007AFF',
    padding: 15,
    borderRadius: 8,
    marginBottom: 10,
    alignItems: 'center',
  },
  clearButton: {
    backgroundColor: '#FF9500',
  },
  statusButton: {
    backgroundColor: '#34C759',
  },
  buttonText: {
    color: 'white',
    fontSize: 16,
    fontWeight: '500',
  },
  infoContainer: {
    marginTop: 20,
    padding: 15,
    backgroundColor: '#e8f4fd',
    borderRadius: 8,
  },
  infoText: {
    fontSize: 14,
    color: '#666',
    textAlign: 'center',
    marginBottom: 5,
  },
})

export default ExampleScreen


